/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pt.ua.miect.sd.simuladorpesca.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.List;
import pt.ua.miect.sd.simuladorpesca.config.SimulationConfig;
import pt.ua.miect.sd.simuladorpesca.conns.SocketWrapper;
import org.apache.log4j.Logger;
import pt.ua.miect.sd.simuladorpesca.config.ServiceConfig;
import pt.ua.miect.sd.simuladorpesca.conns.ConnectionHub;
import pt.ua.miect.sd.simuladorpesca.conns.SocketMessage;
import pt.ua.miect.sd.simuladorpesca.conns.SocketMessageType;
import pt.ua.miect.sd.simuladorpesca.conns.VectorClock;

/**
 *
 * @author PedroA
 */
public class ServerNode implements Runnable{

    private SimulationConfig config;
    private Logger logger;
    private VectorClock clock;

    public ServerNode(SimulationConfig conf)
    {
        this.config = conf;
        logger = Logger.getLogger("ServerNode");
        clock = new VectorClock("SRV");
    }


    @Override
    public void run() {
        logger.info("Starting");
        List<ServiceConfig> services= config.getServices();
        ConnectionHub hub = ConnectionHub.getConnectionHub();
        for (ServiceConfig serviceConfig : services) {
            Socket s;
            try {
                logger.info("Attempting to connect to " + serviceConfig);
                s = new Socket();
                SocketAddress sa = new InetSocketAddress(serviceConfig.getIpAddress(), serviceConfig.getPort());
                s.connect(sa, config.getTimeout());
                logger.info("Connected");
                clock.increment();
            } catch (UnknownHostException ex) {
                logger.error(ex);
                return;
            } catch (IOException ex) {
                logger.error(ex);
                return;
            }
            if (s.isConnected())
            {
                try {
                    logger.info("Creating SocketWrapper");
                    SocketWrapper sw = new SocketWrapper(s, serviceConfig.getService());
                    sw.getOut().writeObject(new SocketMessage(clock.toString(), SocketMessageType.SimulationConfig, config));
                    sw.getOut().flush();
                    logger.info("Message Sent");
                    //stores the connection hub
                    hub.setConnection(serviceConfig.getService(), sw);
                } catch (IOException ex) {
                    logger.error(ex);
                }
            }

        }

    }


}
